﻿using UnityEngine;
using System;
using BestHTTP;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class ParseStudentDataJson
{
    public string token;
}

//自建后台登录
public class HTTPLogin : MonoBehaviour
{
    public Text idText;
    public Text passText;
    public Text defeatText;
    public Button logiBtn;
    public Button registerBtn;
    public GameObject registerObj;
    public string sceneName;

    private float time = 0;
    private bool isDoTweenAni = false;

    private void Start()
    {
        logiBtn.onClick.AddListener(() =>
        {
            StudentLogin();
        });
        registerBtn.onClick.AddListener(() =>
        {
            CreatePanel(registerObj);
        });
    }

    public void StudentLogin()
    {
        login(idText.text, passText.text);
    }

    private void login_ok()
    {
        //登录成功
        checkin();
        CJ.XNFZ.SCORE.ScoreSystemHelper aaa = CJ.XNFZ.SCORE.ScoreSystemHelper.Instance;
        SceneManager.LoadSceneAsync(sceneName);
    }

    public void checkin()
    {
        CJ.XNFZ.SCORE.ScoreSystemHelper.Instance.Checkin();
    }

    private void login_fail(string e)
    {
        //登录失败
        defeatText.text = e;
        defeatText.gameObject.SetActive(true);
        isDoTweenAni = true;
    }

    private void Update()
    {
        if (isDoTweenAni)
        {
            time += Time.deltaTime;
            if (time <= 2)
            {
                defeatText.transform.localPosition += Vector3.Lerp(Vector3.zero, Vector3.up, 1f);
            }
            else
            {
                isDoTweenAni = false;
                time = 0;
                defeatText.gameObject.SetActive(false);
                defeatText.transform.localPosition = Vector3.zero;
            }
        }
    }

    private void CreatePanel(GameObject gameObject)
    {
        GameObject obj = Instantiate(gameObject);
        obj.SetActive(true);
        obj.transform.position = Vector3.zero;
        Destroy(this.gameObject);
    }

    public void login(string username, string passward)
    {
        CJ.XNFZ.Server.XNFZServerHelper.Instance.Login(
            username,
            passward,
            () => {
                Debug.Log("ok");
                CJ.XNFZ.SCORE.ScoreSystemHelper.Instance.userType = CJ.XNFZ.SCORE.ScoreSystemHelper.UserType.student;
                login_ok();
            },
            (string e) => {
                Debug.Log(e);
                login_fail(e);
            }
        );
    }
}